﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            ThreadPool.QueueUserWorkItem(Conn);
            Console.Read();
        }

        private static void Conn(object o)
        {
            while (true)
            {
                TcpClient client = new TcpClient("10.0.5.102", 23456);
                Socket socket = client.Client;
                byte[] buffer = Encoding.UTF8.GetBytes("cmd$in|" + Guid.NewGuid().ToString());
                socket.Send(buffer);
                ThreadPool.QueueUserWorkItem(SandSomell, socket);
            }
        }

        private static void SandSomell(object o)
        {
            var socket = (Socket)o;
            for (int i = 0; i < 50; i++)
            {
                try
                {
                    
                    byte[] buffer = Encoding.UTF8.GetBytes("msg$my|我来了！"+i);
                    socket.Send(buffer);
                    byte[] data = new byte[2048];
                    socket.Receive(data);
                    string req = Encoding.UTF8.GetString(data);
                    if (req.IndexOf("\0")>0)
                    {
                        req = req.Substring(0, req.IndexOf("\0"));
                    }
                    Console.WriteLine(req);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }

            try
            {
                byte[] buffera = Encoding.UTF8.GetBytes("cmd$out|我走了！");
                socket.Send(buffera);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            
        }
    }
}
